/*
 * Copyright (C) 2020 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.internal.platform;

import okhttp3.Protocol;

import javax.annotation.Nullable;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.util.List;

/**
 * Harmony 10+.
 */
public class Ohos10Platform extends OhosPlatform {
    Ohos10Platform(Class<?> sslParametersClass) {
        super(sslParametersClass, null, null, null, null, null);
    }

    @Override
    public void configureTlsExtensions(
            SSLSocket sslSocket, String hostname, List<Protocol> protocols) throws IOException {
        try {
            enableSessionTickets(sslSocket);

            SSLParameters sslParameters = sslSocket.getSSLParameters();

            // Enable ALPN.
            String[] protocolsArray = Platform.alpnProtocolNames(protocols).toArray(new String[0]);
            sslParameters.setProtocols(protocolsArray);

            sslSocket.setSSLParameters(sslParameters);
        } catch (IllegalArgumentException iae) {
            // probably java.lang.IllegalArgumentException: Invalid input to toASCII from IDN.toASCII
            throw new IOException("ohos internal error", iae);
        }
    }

    private void enableSessionTickets(SSLSocket sslSocket) {
    }

    @Override
    public @Nullable
    String getSelectedProtocol(SSLSocket socket) {
        String alpnResult = socket.getSupportedProtocols().toString();

        if (alpnResult == null || alpnResult.isEmpty()) {
            return "";
        }

        return alpnResult;
    }

    public static @Nullable
    Platform buildIfSupported() {
        if (!Platform.isOhos()) {
            return new Platform();
        }
        return null; // Not an Harmony 10+ runtime.
    }
}
